iT邦幫忙

2023 iThome 鐵人賽

DAY 25
0
Mobile Development

30天React Native之旅:從入門到活用系列 第 25

Day 25:本地消息推送(IOS)

  • 分享至 

  • xImage
  •  

IOS推送安裝與配置

  1. 啟用推送功能

    • 打開專案的 .xcworkspace 檔。
    • 點擊「Capabilities」。選擇「Push Notifications」加入。
      https://ithelp.ithome.com.tw/upload/images/20231010/20103365ALE1aJRx3Y.png
  2. 安裝push-notification-ios
    在iOS上我們用push-notification-ios套件,它是針對 iOS 平台的推送通知庫,提供了與 iOS 系統推送通知 API 的直接接口。

    npm i @react-native-community/push-notification-ios --save
    cd ios && pod install
    
  3. 更新AppDelegate.h

    • 在頂部加入以下代碼以引入 User Notifications 框架:
      #import <UserNotifications/UNUserNotificationCenter.h>
      
    • @interface AppDelegate : RCTAppDelegate,替換為以下代碼,讓 AppDelegate 成為 User Notifications 的代理:
      @interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>
      
  4. 更新 AppDelegate.m 或 AppDelegate.mm

    • 引入,在檔案最上方加入:
      #import <UserNotifications/UserNotifications.h>
      #import <RNCPushNotificationIOS.h>
      
    • 加入推送通知相關的方法
      在文件最底部的 @end 之前加入以下代碼:
          // Required for the register event.
         - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
             [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
         }
      
         // Required for the notification event. You must call the completion handler after handling the remote notification.
         - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
             [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
         }
      
         // Required for the registrationError event.
         - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
             [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
         }
      
         // Required for localNotification event
         - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
             [RNCPushNotificationIOS didReceiveNotificationResponse:response];
         }
      
    • 定義 UNUserNotificationCenter
      在 didFinishLaunchingWithOptions 方法中,設置 UNUserNotificationCenter 的代理:
      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
      center.delegate = self;
      
  • 實現接收通知時的行為,在外面再加上以下代碼

    // Called when a notification is delivered to a foreground app.
    -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
        completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    }
    
  • 完整代碼
    這裡AppDelegate.m/mm原生的配置稍微複雜,這裡附上配置完的AppDelegate.mm代碼

    #import "AppDelegate.h"
    #import <UserNotifications/UserNotifications.h>
    #import <RNCPushNotificationIOS.h>
    #import <React/RCTBundleURLProvider.h>
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      self.moduleName = @"AwesomeProject";
      // You can add your custom initial props in the dictionary below.
      // They will be passed down to the ViewController used by React Native.
      self.initialProps = @{};
      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
      center.delegate = self;
      return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    //Called when a notification is delivered to a foreground app.
    -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
    {
      completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    }
    
    - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
    {
    #if DEBUG
      return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
    #else
      return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
    #endif
    }
    // Required for the register event.
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
     [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    }
    // Required for the notification event. You must call the completion handler after handling the remote notification.
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    {
      [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    }
    // Required for the registrationError event.
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
    {
     [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
    }
    // Required for localNotification event
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center
    didReceiveNotificationResponse:(UNNotificationResponse *)response
             withCompletionHandler:(void (^)(void))completionHandler
    {
      [RNCPushNotificationIOS didReceiveNotificationResponse:response];
    }
    @end
    

IOS本地推送實作

  1. 引入 PushNotificationIOS
    import PushNotificationIOS from '@react-native-community/push-notification-ios';
    
  2. 請求推送通知權限
    這會在頁面進來時彈出一個請求推送權限的彈窗
    useEffect(() => {
    PushNotificationIOS.requestPermissions();
    }, []);
    
  3. 撰寫本地推送功能
    我們做一個按鈕,點擊後會推送消息
    const handlePress = () => {
        const notification = {
          id: '1',
          title: "My Notification Title",
          body: "My Notification Message",
          category: "SOME_CATEGORY",
        };
    
        PushNotificationIOS.addNotificationRequest(notification);
    };
    
    
    return (
    <View style={styles.container}>
      <Button title="Send Local Notification" onPress={handlePress} />
    </View>
    );
    
  4. 完成!
    https://ithelp.ithome.com.tw/upload/images/20231010/20103365fXoQKgerIG.png

上一篇
Day 24:取得Apple開發者憑證
下一篇
Day 26:React Native 中集成生物辨識
系列文
30天React Native之旅:從入門到活用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言